<template>
    <div>
        <el-dialog v-model="show" :title="''" :close-on-click-modal="false" @close="emit('update:show', false)"
            :show-close="tabLength > 0" :close-on-press-escape="tabLength > 0" :width="600" top="5vh">
            <div style="margin: 10px;text-align:center;cursor: default;">
              <span style="color: red;font-family: 微软雅黑;font-weight: 600;font-size:28px">D<span style="color:#409EFF;font-weight:400">b</span></span><span style="text-align: center;font-size: 26px;color:#333;font-weight: 200;font-family: sans-serif;">Box</span>
            </div>
            <el-row style="margin: 10px">
              <el-button type="primary" size="small" @click="newConn">新增</el-button>
            </el-row>
            <el-table :data="conns" size="small" highlight-current-row :border="true" height="260" empty-text="无数据">
                <el-table-column type="index" width="50" align="center" />
                <el-table-column label="Action" width="180">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="chose(scope)">连接</el-button>
                        <el-button type="text" size="small" @click="StarEdit(scope.row)">编辑</el-button>
                        <el-popconfirm @confirm="del(scope.row.name)" title="确认要删除吗?">
                            <template #reference>
                                <el-button type="text" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="Name" width="200" :show-overflow-tooltip="true" />
                <el-table-column prop="type" label="Type" width="120" :show-overflow-tooltip="true"  />
            </el-table>
            <template #footer>
                <div>@ 2022 DbBox 0.1 beta 数据库盒子 www.DbBox.cc Copyright</div> 
            </template>
        </el-dialog>

        <el-dialog v-model="showEditor" title="配置连接" draggable :close-on-click-modal="false" :width="720" top="8vh">
            <div class="dialog-content">
                <el-tabs tab-position="left" style="height: auto; " class="demo-tabs" :addable="false"
                :closable="false" v-model="tabActive" >
                    <el-tab-pane :label="form[0].type" :name="form[0].type" :disabled="edit_name != ''">
                        <el-form :model="form[0]" label-width="120px" size="small">
                            <el-form-item label="名称">
                                <el-input v-model="form[0].name" />
                            </el-form-item>
                            <el-form-item label="服务器地址">
                                <el-input v-model="form[0].server" />
                            </el-form-item>
                            <el-form-item label="端口">
                                <el-input v-model="form[0].port" />
                            </el-form-item>
                            <el-form-item label="连接类型">
                                <el-radio-group v-model="form[0].connect_type">
                                    <el-radio label="servername">服务名</el-radio>
                                    <el-radio label="sid">SID</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="服务名" v-if="form[0].connect_type == 'servername'">
                                <el-input v-model="form[0].servername" />
                            </el-form-item>
                            <el-form-item label="SID" v-if="form[0].connect_type == 'sid'">
                                <el-input v-model="form[0].sid" />
                            </el-form-item>
                            <el-form-item label="用户名">
                                <el-input v-model="form[0].username" />
                            </el-form-item>
                            <el-form-item label="密码">
                                <el-input v-model="form[0].password" type="password" />
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane :label="form[1].type" :name="form[1].type" :disabled="edit_name != ''">
                        <el-form :model="form[1]" label-width="120px" size="small">
                            <el-form-item label="名称">
                                <el-input v-model="form[1].name" />
                            </el-form-item>
                            <el-form-item label="文件地址">
                                <el-input v-model="form[1].file" class="input-with-select">
                                    <template #append>
                                        <el-button :icon="Document" @click="selectFile" />
                                    </template>
                                </el-input>

                            </el-form-item>
                            <el-form-item label="版本">
                                <el-radio-group v-model="form[1].version">
                                    <el-radio :label="3">3</el-radio>
                                    <el-radio :label="2" disabled>2</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="密码">
                                <el-input v-model="form[1].password" type="password" />
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane :label="form[2].type" :name="form[2].type" :disabled="edit_name != ''">
                        <el-form :model="form[2]" label-width="120px" size="small">
                            <el-form-item label="名称">
                                <el-input v-model="form[2].name" />
                            </el-form-item>
                            <el-form-item label="服务器地址">
                                <el-input v-model="form[2].server"  />
                            </el-form-item>
                            <el-form-item label="端口">
                                <el-input v-model="form[2].port" placeholder="1433" />
                            </el-form-item>
                            <el-form-item label="实例服务名">
                                <el-input v-model="form[2].servername" placeholder="MSSQLSERVER" />
                            </el-form-item>
                            <el-form-item label="初始数据库名">
                                <el-input v-model="form[2].dbname" placeholder="master" />
                            </el-form-item>
                            <el-form-item label="用户名">
                                <el-input v-model="form[2].username" />
                            </el-form-item>
                            <el-form-item label="密码">
                                <el-input v-model="form[2].password" type="password" />
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane :label="form[3].type" :name="form[3].type" :disabled="edit_name != ''">
                        <el-form :model="form[3]" label-width="120px" size="small">
                            <el-form-item label="名称">
                                <el-input v-model="form[3].name" />
                            </el-form-item>
                            <el-form-item label="服务器地址">
                                <el-input v-model="form[3].server"  />
                            </el-form-item>
                            <el-form-item label="端口">
                                <el-input v-model="form[3].port" placeholder="3306" />
                            </el-form-item>
                            <el-form-item label="数据库名">
                                <el-input v-model="form[3].dbname" placeholder="" />
                            </el-form-item>
                            <el-form-item label="用户名">
                                <el-input v-model="form[3].username" />
                            </el-form-item>
                            <el-form-item label="密码">
                                <el-input v-model="form[3].password" type="password" />
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </div>
            <template #footer>
                <el-button size="small" type="primary" @click="submit">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<style scoped>
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
</style>
<script setup>
import {post} from '/src/utils/http'
import { ElMessage } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import { computed, watch,defineProps, defineEmits, onMounted, toRefs, nextTick, ref } from 'vue'

const props = defineProps({
    show:Boolean,
    callback: Function,
    tabLength: Number
})

const { show,callback,tabLength } = toRefs(props)

const emit = defineEmits(['callback'])

// { name: 'UAT-RDS', type: 'Oracle', server: '10.1.16.21', port:1521, connect_type: 'servername', servername: 'iotuatdb.mindray.com', username: 'IOT_RDS_CN', password: 'VaGQK2FL' },
// { name: 'UAT-SUB', type: 'Oracle', server: '10.1.8.91', port:1521, connect_type: 'sid', sid: 'iotsubdb', username: 'IOT_SUB_ALL', password: '7@%<(Ci3' },
// { name: 'mysqlite', type: 'Sqlite', file: 'd:\temp.db', version: 3 },
const conns = ref([])
const showEditor = ref(false)
const edit_name = ref('')
const tabActive = ref('Oracle')
const form = ref([
        {
            type: 'Oracle',
            name: '',
            server: '',
            port:　1521,
            connect_type: 'servername',
            sid: '',
            username: '',
            password: ''
        },
        {
            type: 'Sqlite',
            name: '',
            file: '',
            version: 3,
            password: ''
        },
        {
            type: 'Sqlserver',
            name: '',
            server: '',
            port: 1433,
            servername: 'MSSQLSERVER',
            dbname: 'master',
            username: '',
            password: ''
        },
        {
            type: 'Mysql',
            name: '',
            server: '',
            port: 3306,
            dbname: '',
            username: '',
            password: ''
        },
    ])

const currentForm = computed(() => form.value.filter(o => o.type == tabActive.value)[0])

function refresh(){
    post('/api/DbConn/GetConns', {}).then((res) => {
        if(res && res.flag) { 
            conns.value = res.data.map(o => JSON.parse(o.data))
        } else {
            ElMessage({ 
                message: res.logs.join(','),
                type: 'error',
            })
        }
    })
}
function newConn(){
    showEditor.value = true
}
function chose(scope){
    var conn = scope.row
    if(conn.type == 'Oracle') { 
        if(conn.servername)
            conn.DbConnStr = `Data Source=${conn.server}:${conn.port}/${conn.servername};User Id=${conn.username};Password=${conn.password};Connection Lifetime=600;Min Pool Size=0;Incr Pool Size=1;Pooling=False`
        else
            conn.DbConnStr = `Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=${conn.server})(PORT=${conn.port}))(CONNECT_DATA=(SID=${conn.sid})));User Id=${conn.username};Password=${conn.password};Connection Lifetime=600;Min Pool Size=0;Incr Pool Size=1;Pooling=False`
    }
    if(conn.type == 'Sqlite') { 
        if(conn.password)
            conn.DbConnStr = `Data Source=${conn.file};Pooling=False;Password=${conn.password}`
        else
            conn.DbConnStr = `Data Source=${conn.file};Pooling=False`
    }
    if(conn.type == 'Sqlserver') { 
        conn.DbConnStr = `Data Source=${conn.server},${conn.port};Initial Catalog=${conn.dbname};User ID=${conn.username};Password=${conn.password}`
    }
    if(conn.type == 'Mysql') { 
        conn.DbConnStr = `Data Source=${conn.server};Port=${conn.port};Database=${conn.dbname};User ID=${conn.username};Password=${conn.password}`
    }
    emit('callback', scope.row)
}

function selectFile(){
    // var input = document.createElement('input')
    // input.type = 'file'
    // input.accept = '.db,.db3,.sqlite,.sqlite3'
    // input.addEventListener('change', e => {
    //     //value is c:\fakepath\file
    //     //this.form[1].file = e.target.value
    //     setTimeout(() => {
    //         if(window.ofd_file) {
    //             form.value[1].file = window.ofd_file
    //         }
    //     }, 20)
    // })
    //input.click()
    window.cs.selectFile().then(a => {
        form.value[1].file = a
    })
}
function submit(){
    var param = {
        edit_name: edit_name.value,
        name: currentForm.value.name,
        data: JSON.stringify(currentForm.value)
    }
    post('/api/DbConn/' + (edit_name.value ? 'Update': 'Add'), param).then((res) => {
        if(res && res.flag) { 
            showEditor.value = false
            refresh()
        } else {
            ElMessage({ 
                message: res.msg,
                type: 'error',
            })
        }
    })
}
function StarEdit(row) {
    edit_name.value = row.name
    tabActive.value = row.type
    showEditor.value = true
    nextTick(() => {
        for(var k in row) {
            currentForm.value[k] = row[k]
        }
    })
}
function del(name){
    post('/api/DbConn/Delete', { name }).then((res) => {
        if(res && res.flag) { 
            showEditor.value = false
            refresh()
        } else {
            ElMessage({ 
                message: res.msg,
                type: 'error',
            })
        }
    })
}

onMounted(refresh)

const oldForm = JSON.stringify(form.value)
watch(() => showEditor.value, val => {
    if(!val) { 
        edit_name.value = ''
        tabActive.value = 'Oracle'
        form.value = JSON.parse(oldForm)
    }
})
</script>
